import pyvisa
from time import sleep

class GPIBPortTool():
    def __init__(self,gpib_address,debugPrint):
        self.debugprint = debugPrint
        self.address = gpib_address
        self.gpibDevice = None
        self.rcvLine  = ""
        self.demoCmd1 = "VOLT 0.5"      #channel 1 output 1.0V
        self.demoCmd2 = "VOLT 1.0"
        self.demoCmd3 = "VOLT 1.5"
        self.demoCmd4 = "VOLT 2.0"
        self.demoCmd5 = "VOLT2 2.0"     #channel 2 output 2.0V     
        self.demoCmd6 = "CURR 0.01"     #channel 1 output current limit to 0.1A
        self.demoCmd7 = "CURR2 0.01"    #channel 2 output current limit to 0.1A        
        self.EnableOut = "OUTP ON"
        self.DisableOut= "OUTP OFF"
        self
        
    def initDevice(self):
        device = pyvisa.ResourceManager()
        self.gpibDevice = device.open_resource(self.address)
        status = self.gpibDevice.query('*IDN?')
        if self.debugprint == 1:
            print(status)
        
        status = self.gpibDevice.write('*RST')
        status = self.gpibDevice.write('*CLS')
        status = self.gpibDevice.write('STAT:PRES')
        status = self.gpibDevice.write('*SRE 0')
        status = self.gpibDevice.write('*ESE 0')

        
    def gpibDeviceSend(self,message):
        try:
            s = self.gpibDevice.write(message)
#            s = self.gpibDevice.write(message + "\r\n")
            if self.debugprint == 1:
                print(s)
        except IOError as e:
                print(e)
                self.gpibDevice.close()
                
    def gpibDeviceRead(self, nTime):
        n = 0
        while(n<nTime):
            line = self.gpibDevice.readline().strip()
            self.rcvLine = self.rcvLine + line
            if self.debugprint == 1:
                print(self.rcvLine)
            n = n + 1
        return self.rcvLine

    def current_limit(self,limitValue):
        cmd = "CURR " + str(limitValue)
        status = self.gpibDevice.write(cmd)
        
    def disable_output(self):
        status = self.gpibDevice.write("OUTP OFF")
    
    def enable_output(self):
        status = self.gpibDevice.write("OUTP ON")        
        
        
if __name__ == '__main__':
    aglient_pwr = GPIBPortTool('GPIB0::2::INSTR',0)
    aglient_pwr.initDevice()
    aglient_pwr.enable_output()
    sleep(1)
    aglient_pwr.gpibDeviceSend(aglient_pwr.demoCmd1)
    sleep(1)
    aglient_pwr.gpibDeviceSend(aglient_pwr.demoCmd2)
    sleep(1)
    aglient_pwr.gpibDeviceSend(aglient_pwr.demoCmd3)
    sleep(1)
    aglient_pwr.gpibDeviceSend(aglient_pwr.demoCmd4)
    sleep(1)
    aglient_pwr.current_limit(0.2)
    aglient_pwr.disable_output()    
    
    
    
    
    
    
    
    